after_sram_detection:
	ld		a,[slotvar]
	call	change_slot_page1
 
	ret
 
 
 
	
sram_detection:
	;clean variables
	xor		a
	ld		[sram_slot_page1],a
	ld		[sram_found],a

	ld		b,4
sram_detection_loop:
	ld		a,b
	dec		a
	ld		d,a
	call	read_subslot_conf
	jr		nc,nosubslots							;nc ... not subslots
	push	bc
	call	change_slot_and_test
	pop		bc
comeback_from_nosubslots:
	ld		a,[sram_found]
	inc		a
	jr.		z,after_sram_detection					;sram found , return

	djnz	sram_detection_loop					
	
	jr.		after_sram_detection
	;ret
	
	
read_subslot_conf:
	push	bc
	ld		c,a
	ld		b,0
	ld		hl,0xFCC1
	add		hl,bc
	ld		a,[hl]
	and		0x80
	or		c
	rlca	
	pop		bc

	ret
	
	
	
change_slot_and_test:
	ld		e,d
	ld		b,0x04
change_slot_and_test_loop:	
	ld		a,b
	dec		a
	rlca	
	rlca
	or		e
	or		0x80
	ld		d,a
	call	change_slot_page1
	push	de									;preserve e
	call	test_sram
	pop		de
	ret		z
	djnz	change_slot_and_test_loop

	ret


; a holds slot/subslot info
change_slot_page1:
	push	af
	push	hl
	push	de
	push	bc
	ld		h,0x40
	call	0x24				;ENASLT
	;Function : Switches indicated slot at indicated page on perpetual
	;Input    : A  - ExxxSSPP
	;				+-?------ 
	;		   H - Bit 6 and 7 must contain the page number (00-11)	
	pop		bc
	pop		de
	pop		hl
	pop		af

	ret



test_sram:
	ld		a,0x69
	ld		[0x5fff],a
	ld		a,0x4d
	ld		[0x5ffe],a

	ld		hl,0x5880
	ld		e,[hl]
	ld		a,e
	cpl		
	ld		[hl],a
	ld		a,[hl]
	cpl
	cp		e
	ret		nz
	ld		[hl],e							;restore original value
	
	;checking if it's just RAM
	xor		a
	ld		[0x5fff],a
	ld		a,[hl]
	ld		e,a
	inc		a
	ld		[hl],a
	ld		a,[hl]
	cp		e
	ret		nz								;ret if it's RAM
	ld		a,0xff
	ld		[sram_found],a
	ld		a,d
	ld		[sram_slot_page1],a
	
	ret


nosubslots:
	ld		a,d
	call	change_slot_page1
	push	de								;preserve e
	call	test_sram
	pop		de
	
	jr		comeback_from_nosubslots
	ret

;saveload_buffer must be already updated
savegame_on_sram:
	call	set_and_activate_SRAM

	;operations on SRAM 
	ld		hl,saveload_buffer
	ld		de,0x4000
	ld		bc,115								;savegame block size
	ldir
	
	call	deactivate_and_unset_SRAM
	
	ret

;updates saveload_buffer from sram
loadgame_from_sram:
	call	set_and_activate_SRAM
	
	;operations on SRAM 
	ld		hl,0x4000
	ld		de,saveload_buffer
	ld		bc,115								;savegame block size
	ldir
	
	call	deactivate_and_unset_SRAM

	ret


set_and_activate_SRAM:
	;set SRAM page
	di
	ld		a,[sram_slot_page1]
	call	change_slot_page1
	ei

	;activate SRAM
	ld		a,0x69
	ld		[0x5fff],a
	ld		a,0x4d
	ld		[0x5ffe],a
	
	ret

deactivate_and_unset_SRAM:
	;deactivate SRAM
	xor		a
	ld		[0x5fff],a

	;come back to normal page
	di
	ld		a,[slotvar]
	call	change_slot_page1
	ei

	ret

;relocatable_routines_end:

